﻿
//#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
//#include <objidl.h>

#include <commctrl.h>
#include <mmsystem.h>
#include <sstream>
#include <shlobj.h>   
#include <atlstr.h>


//#include "customWM.h"
#include "resource.h"
#include "playlist.h"
#include "MediaPlayControler.h"
#include "FPSLimiter.h"

#include "Config.h"


#include "Panel.h"
#include "Button.h"
#include "ColumnsAndTime.h"
#include "Slider.h"
#include "PlaylistMenu.h"
#include "SlidingText.h"







#pragma comment( lib, "winmm" )

#pragma comment (lib, "comctl32.lib")



HANDLE m_hStartEvent; // vieno instance paleidimui

int lastTime;	// spektrometrui
int lastFileAddTime; // failu pridejimui is keliu programu instancu


PAINTSTRUCT ps;
HDC hdc;


// Global variables

enum { 
	ID_BUTTON_PREV, 
	ID_BUTTON_PLAY, 
	ID_BUTTON_PAUSE, 
	ID_BUTTON_STOP, 
	ID_BUTTON_NEXT, 
	ID_BUTTON_MINIMIZE, 
	ID_BUTTON_CLOSE, 
	ID_BUTTON_HELP, 
	ID_BUTTON_SHUFLE, 
	ID_BUTTON_SAVE,
	ID_BUTTON_LOAD,


	ID_PROGRESS_BAR, 
	ID_VOLUME_BAR};

HINSTANCE g_hInst;




float fl[64];




Config config = Config();

PlayList playlist = PlayList(&config);

MediaPlayControler *player;



// lango dydziai
int windowWidth = 488;
int windowHeight = 145;

// NEW
Panel	basePanel(0, 0, windowWidth, windowHeight);
ColumnsAndTime *colAndTime;
Slider *progresSlider;
Slider *soundSlider;
PlaylistMenu *playlistMenu;
SlidingText *slidingText;





int cmdShow;


// PROGRESBARO POZICIJOS
int progBarTop = 125;
int progBarLeft = 5;
int progBarWidth = 250;
int progBarHeight = 10;

// SOUNDBARO POZICIJOS
int soundBarTop = 170;
int soundBarLeft = 130;
int soundBarWidth = 125;
int soundBarHeight = 20;

bool clearBackground = true;

////////////////////////

// lango valkiojimui su pele (kai paspaustas mygtukas)
bool mButtonDown = false;
LPPOINT tmpPoint = new POINT;

int tmX;
int tmY;





// The main window class name.
static TCHAR szWindowClass[] = _T("win32appIPlay");

// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("Audio failų grotuvas");

HINSTANCE hInst;

// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);


bool nextForward = true; // dainos keitimui, kad esant blogoms dainoms eitu atgal kol ras gera, o tada vel testu sokinejima pirmyn


VOID OnPaint(HDC hdc)
{
   

	basePanel.Draw(hdc);
	
   
}








wstring openfilename(string type, WCHAR *filter = L"Playlist files (*.pls)\0*.pls\0", HWND owner = NULL) {

  OPENFILENAME ofn;
  WCHAR fileName[MAX_PATH] = L"";
  ZeroMemory(&ofn, sizeof(ofn));

  ofn.lStructSize = sizeof(OPENFILENAME);
  ofn.hwndOwner = owner;
  ofn.lpstrFilter = filter;
  ofn.lpstrFile = fileName;
  ofn.nMaxFile = MAX_PATH;
  
  if(type == "open")
  {
		ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
  }
  if(type == "save")
  {
	  ofn.Flags = OFN_NOCHANGEDIR | OFN_CREATEPROMPT | OFN_OVERWRITEPROMPT ;
  }
  ofn.lpstrDefExt = L"";

  wstring fileNameStr;

  if(type == "open")
  {
  if ( GetOpenFileName(&ofn) )

    fileNameStr = fileName;
  }

  if(type == "save")
  {
  if ( GetSaveFileName(&ofn) )
  {

	  
    fileNameStr = fileName;
	//OutputDebugString(fileNameStr.c_str());
  }
  }


  return fileNameStr;

}




BOOL CheckOneInstance()
{
	
    m_hStartEvent = CreateEventW( NULL, TRUE, FALSE, L"IPlayer_Grotuvas");
    if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
        CloseHandle( m_hStartEvent ); 
        m_hStartEvent = NULL;
        // already exist
        // send message from here to existing copy of the application
        return FALSE;
    }
    // the only instance, start in a usual way
    return TRUE;
}






int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
	
	//new Button(5, 5, 5, 5);
	//AddFontResourceEx(L"C:\\Ventouse.ttf", FR_PRIVATE, NULL);


	LPWSTR *szArgList;
	int argCount;
	szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);

	if(!CheckOneInstance())
	{
		
		//// procesas rastas. Usiimam zinutes persiuntimu
		//LRESULT copyDataResult;
		HWND hWndOther = FindWindow(szWindowClass, szTitle);

		

		for(int i = 1; i < argCount; i++)
		{

			LPWSTR lpszString = szArgList[i];;
			//lpszString = szArgList[i];
			COPYDATASTRUCT cds;
			cds.dwData = 1; // can be anything
			cds.cbData = sizeof(WCHAR) * (_tcslen(lpszString) + 1);
			cds.lpData = (void*)lpszString;
			SendMessage(hWndOther, WM_COPYDATA, (WPARAM)hWndOther, (LPARAM)(LPVOID)&cds);
			

		}

		return 0;
	}


	/*AddFontResource(L"C:\\Ventouse.ttf");
	SendMessage( HWND_BROADCAST,  WM_FONTCHANGE, 0, 0 );*/

    WNDCLASSEX wcex;
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR           gdiplusToken;

	// Initialize GDI+.
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style          = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
	wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground  = (HBRUSH)GetStockObject(GRAY_BRUSH);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_ICON1));


	

    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

    hInst = hInstance; // Store instance handle in our global variable
	
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
		WS_POPUPWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        windowWidth, windowHeight,
        NULL,
        NULL,
        hInstance,
        NULL
    );

	///////////////
	RAWINPUTDEVICE Rid[2];

	// Keyboard
	Rid[0].usUsagePage = 1;
	Rid[0].usUsage = 6;
	Rid[0].dwFlags = 0;
	Rid[0].hwndTarget=NULL;

	// Mouse
	Rid[1].usUsagePage = 1;
	Rid[1].usUsage = 2;
	Rid[1].dwFlags = 0;
	Rid[1].hwndTarget=hWnd;
	

    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);

        return 1;
    }

	
	LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
	lStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
	SetWindowLong(hWnd, GWL_STYLE, lStyle);

	/*WS_CAPTION is defined as (WS_BORDER | WS_DLGFRAME). You can get away with removing just these two styles, since the minimize maximize and sytem menu will disappear when the caption disappears, but it's best to remove them as well. 

	It's also best to remove the extended border styles.*/
	
	LONG lExStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
	lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
	SetWindowLong(hWnd, GWL_EXSTYLE, lExStyle);

	SetWindowPos(hWnd, NULL, 0,0,0,0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);

    

	if(config.getInt("WindowPositionX") < 0 || config.getInt("WindowPositionX") > GetSystemMetrics(SM_CXSCREEN)- windowWidth/2 ||
		config.getInt("WindowPositionY") < 0 || config.getInt("WindowPositionY") > GetSystemMetrics(SM_CYSCREEN)- windowHeight/2)
	{
		config.setInt("WindowPositionX", (GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2);
		config.setInt("WindowPositionY", (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
	}

	//config.setInt("WindowPositionX", 10);
		//config.setInt("WindowPositionY", 10);

    MoveWindow(hWnd,
				config.getInt("WindowPositionX"),
				config.getInt("WindowPositionY"),
				windowWidth,
				windowHeight,
				TRUE);

	// The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
	cmdShow = nCmdShow;
    ShowWindow(hWnd, nCmdShow);


	if (RegisterRawInputDevices(Rid,2,sizeof(RAWINPUTDEVICE))==FALSE)
	{
		MessageBox(NULL, L"Input device error", L"Klaida", MB_ICONERROR);
	}
    UpdateWindow(hWnd);

	DragAcceptFiles(hWnd, true);

	player = new MediaPlayControler();


	playlist.loadPlaylist(L"playlist.pls");
	//playlist.LoadDefaultPlaylist();

	playlist.setSongPlace(config.getInt("LastSongId"));
	playlist.setShuffle(config.getInt("Shuffle"), true);


	for(int i = 1; i < argCount; i++)
		{

			LPWSTR lpszString = szArgList[i];;
			//lpszString = szArgList[i];
			COPYDATASTRUCT cds;
			cds.dwData = 1; // can be anything
			cds.cbData = sizeof(WCHAR) * (_tcslen(lpszString) + 1);
			cds.lpData = (void*)lpszString;
			SendMessage(hWnd, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)(LPVOID)&cds);

		}


	//playlist.setShuffle(true);
	//playlist.setSongPlace(0);
	playlistMenu->Update();

	
	bool firstrun = true;

    // Main message loop:
	bool suktis = true;
    MSG msg;
	ZeroMemory( &msg, sizeof(msg) );

	FPSLimiter *FPS = new FPSLimiter(30);

	while(suktis )
	{	
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if(msg.message == WM_QUIT) suktis = false;
		}

		if(msg.message == WM_QUIT || msg.message == WM_CLOSE)
		{
			//if(MessageBox(NULL, L"Issaugoti grojarasti?", L"Close", MB_OKCANCEL) == true) playlist.savePlayList();
			//playlist.savePlayList();
			//break;
		}


		if(player != NULL)
		{
			if(!player->isPlaying())
			{
				if(firstrun)
				{
					//playlist.next();
					//playlist.setSongPlace(config.getInt("LastSongId"));
					MusicFileData song = playlist.getSong(playlist.getCurrentSongId());	;
					player->load(song.filePath);
					slidingText->setName(player->getName());
					player->setProgres(config.getFloat("LastSongProgress"));
					player->setVolume(config.getFloat("SoundLevel"));
					if(config.getInt("Pause") == 1) player->pause();
					playlistMenu->setTop(playlist.getCurrentSongId());

					//stulpeliai->setDrawMode(config.getInt("VisualizationID"));
					colAndTime->setDrawMode(config.getInt("VisualizationID"));
					
					firstrun = false;
				}
				else
				{
				//MusicFileData song = playlist.next();
				MusicFileData song;
					if(nextForward)
					{ 
						song = playlist.next();
					}
					else
					{
						song = playlist.prev();	
					}

				player->load(song.filePath);
				slidingText->setName(player->getName());
				//if(playlist.isShufled())
					//config.setInt("LastSongId", 0);
				//else
					config.setInt("LastSongId", playlist.getCurrentSongId());
				}
			}
			else
			{
				nextForward = true;
				slidingText->setName(player->getName());
				float soundProgress = player->getProgres()*100;
				float volumeLevel = player->getVolume()*100;
				

				//if((int)soundProgress != (int)progresSlider->getProgress()) progresSlider->Update();
				//if((int)volumeLevel != (int)soundSlider->getProgress()) soundSlider->Update();

				

				soundSlider->setProgress(volumeLevel);
				progresSlider->setProgress(soundProgress);

				//config.setFloat("LastSongProgress", progressBar->getProgress()/100);
				config.setFloat("LastSongProgress", progresSlider->getProgress()/100);

				//soundBar->setProgress(volumeLevel);

				if(!player->isUpdated())
				{
					//char *c = ;
					wstring str = player->getName();
					/*for(int i = 0; i < 255; i++)
					{
						str += c[i];
					}*/		
					playlist.updateSongData(playlist.getCurrentSongId(), str, player->getLength()/1000);
					//delete[] c;
					playlistMenu->Update();
				}
			}
		

		//float *fl = new float[64];
		player->getSpectrum(fl, 64);
		//stulpeliai->update(fl, player->getPos());
		colAndTime->UpdateColumnData(fl, player->getPos());
		slidingText->Update();
		//delete[] fl;

		basePanel.Hover();
		FPS->doSleep();
		//Sleep(30);
		}
		//SendMessage(hWnd, WM_COMMAND, ID_BUTTON_NEXT, 0);
		

		
	}

	
	
	config.setInt("VisualizationID", colAndTime->getDrawMode());

	delete FPS;
	delete player;
	
	

	DragAcceptFiles(hWnd, false);
	GdiplusShutdown(gdiplusToken);
	CloseHandle( m_hStartEvent );
    return (int) msg.wParam;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

	INITCOMMONCONTROLSEX InitCtrlEx;

	InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
	InitCtrlEx.dwICC  = ICC_PROGRESS_CLASS;
	InitCommonControlsEx(&InitCtrlEx);


	


    switch (message)
    {
	case WM_CREATE:
		{
			
			//									x		y		width	height
			//stulpeliai		= new Stulpeliai	(8,		17,		255,	72,		64, hWnd);
			//playlistMenuOLD	= new PlaylistMenuOLD	(267,	17,		278,	121,	&playlist, hWnd);
			//playBox			= new NowPlaying	(8,		92,		255,	15,		hWnd);
			//progressBar		= new ProgressBar	(8,		110,	255,	10,		hWnd, ID_PROGRESS_BAR);		
			//soundBar		= new ProgressBar	(130,	123,	133,	15,		hWnd, ID_VOLUME_BAR);
			
			// mygtukai

			//buttons = new Button[5];

			int btnH = 113;
			int btnW = -14;
			int btnStep = 18;

			//basePanel.addChild(new Button(5, 5, 21, 15, hWnd, ID_BUTTON_PREV,	L"img\\buttons.bmp", 0, 0));


			Panel *subPanel = new Panel(4, 12, 480, 129);

			// new
			//													x		y		width	height


			//basePanel.addChild(subPanel);

			subPanel->addChild(colAndTime	= new ColumnsAndTime(4,		4,		192,	75,		64, hWnd));
			subPanel->addChild(progresSlider= new Slider		(4,		100,		192,	11,		hWnd, ID_PROGRESS_BAR, L"img\\buttons.bmp", 0, 14));
			subPanel->addChild(soundSlider	= new Slider		(102,	113,	94, 	13,		hWnd, ID_VOLUME_BAR, L"img\\buttons.bmp", 0, 14));
			subPanel->addChild(playlistMenu	= new PlaylistMenu	(198,	4,		278,	108,	hWnd, &playlist, L"img\\buttons.bmp", 10, 14));
			subPanel->addChild(slidingText	= new SlidingText	(4,		82,		192,	15,		hWnd));
			

			subPanel->addChild(new Button(btnW+=btnStep, btnH, 17, 13, hWnd, ID_BUTTON_PREV,	L"img\\buttons.bmp", 0, 0));
			subPanel->addChild(new Button(btnW+=btnStep, btnH, 17, 13, hWnd, ID_BUTTON_PLAY,	L"img\\buttons.bmp", 17, 0));
			subPanel->addChild(new Button(btnW+=btnStep, btnH, 17, 13, hWnd, ID_BUTTON_PAUSE,	L"img\\buttons.bmp", 34, 0));
			subPanel->addChild(new Button(btnW+=btnStep, btnH, 17, 13, hWnd, ID_BUTTON_STOP,	L"img\\buttons.bmp", 51, 0));
			subPanel->addChild(new Button(btnW+=btnStep, btnH, 17, 13, hWnd, ID_BUTTON_NEXT,	L"img\\buttons.bmp", 68, 0));

			subPanel->addChild(new Button(198,				btnH, 26, 13, hWnd, ID_BUTTON_SAVE,		L"img\\buttons.bmp", 18, 14)); // save
			subPanel->addChild(new Button(229,				btnH, 25, 13, hWnd, ID_BUTTON_LOAD,		L"img\\buttons.bmp", 45, 14)); // load
			subPanel->addChild(new Button(259,				btnH, 34, 13, hWnd, ID_BUTTON_SHUFLE,	L"img\\buttons.bmp", 71, 14)); // shufle


			basePanel.addChild(new Button(basePanel.getDimensions()->width-22,	2, 7, 7, hWnd, ID_BUTTON_MINIMIZE,	L"img\\buttons.bmp", 85, 0)); // _
			basePanel.addChild(new Button(basePanel.getDimensions()->width-11,	2, 7, 7, hWnd, ID_BUTTON_CLOSE,		L"img\\buttons.bmp", 99, 0)); // X
			basePanel.addChild(new Button(4,				2, 7, 7, hWnd, ID_BUTTON_HELP,		L"img\\buttons.bmp", 106, 0)); // ?
			
			
			

			basePanel.addChild(subPanel);


			
			break;
		}
    case WM_PAINT:
		{

			if(mButtonDown)
			{
				LPPOINT pt = new POINT;
				GetCursorPos(pt);

				int deltaX = pt->x - tmpPoint->x;
				int deltaY = pt->y - tmpPoint->y;


				MoveWindow(hWnd, (tmX + deltaX), (tmY + deltaY), windowWidth, windowHeight, true);
				config.setInt("WindowPositionX", (tmX + deltaX));
				config.setInt("WindowPositionY", (tmY + deltaY));
				SetFocus(hWnd);
				//playlistMenuOLD->update();
				//progressBar->update();
				//soundBar->update();
				delete[] pt;
			}
				
			hdc = BeginPaint(hWnd, &ps);

			Graphics    graphics(hdc);


			OnPaint(hdc);		
			EndPaint(hWnd, &ps);
			break;
		}

	case WM_ERASEBKGND:
		{
			if(!mButtonDown)
			{
				basePanel.UpdateGraphics();
			}
			//hdc = BeginPaint(hWnd, &ps);
			//Graphics    graphics(hdc);

			//Pen		penBlackBorder(Color(255, 0, 0, 0));
			//SolidBrush	brushFatBorder(Color(255, 102, 102, 102));
			//SolidBrush	brushInsideFill(Color(255, 68, 68, 68));

			//	

			//// big block
			//// outside border
			//graphics.DrawRectangle(&penBlackBorder, 0, 0, windowWidth-1, windowHeight-1);
			//// border fill
			//graphics.FillRectangle(&brushFatBorder, 1, 1  , windowWidth-2, windowHeight-2);
			//// inside border
			//graphics.DrawRectangle(&penBlackBorder, 4, 13, windowWidth-1-4-4, windowHeight-1-4-13);
			//// inside fill
			//graphics.FillRectangle(&brushInsideFill, 4+1, 13+1  , windowWidth-2-4-4, windowHeight-2-4-13);

			//graphics.DrawString(L"Audio failų grotuvas", -1, &Font(&FontFamily(L"Arial"), 11, FontStyleRegular, UnitPixel), PointF(34, 0), &SolidBrush(Color(150, 204, 204, 204)));

			////graphics.FillRectangle(&SolidBrush(Color(255, 70, 50, 80)), 0, 0  , windowWidth, windowHeight);

			//// mygtuku paisymas
			//for(int i = 0; i < buttons_count; i ++)
			//{
			//	buttons[i]->draw(hdc);
			//}

			////playlistMenuOLD->scroll(0, true);
			//playlistMenuOLD->update();
			//stulpeliai->click();
			//progressBar->update();
			//soundBar->update();

			//stulpeliai->draw(hdc);
			//playBox->draw(hdc);

			//EndPaint(hWnd, &ps);
			break;
		}



	case WM_DROPFILES:
		{
			//playlist.setAddRunning(true);
			HDROP query = (HDROP) wParam;
			int n = 0, count = DragQueryFile( query, 0xFFFFFFFF, 0, 0 );
			while ( n < count )
			{

				WCHAR file[MAX_PATH];
				DragQueryFileW( query, n, file, 512 );
				MusicFileData temp;
				temp.filePath = file;


				int lastSlash = 0;
				int lastPoint = MAX_PATH;
				for(int i = 0; i < MAX_PATH; i ++)
				{
					if(file[i] == L'\\')
					{
						lastSlash = i;
					}
					if(file[i] == L'\0') break;
				}
				

				for(int i = lastSlash; i < MAX_PATH; i ++)
				{
					
					if(file[i] == L'.')
					{
						lastPoint = i; //break;
					}
					if(file[i] == L'\0') break;
				}
				if(file[lastPoint+1] == L'p' && file[lastPoint+2] == L'l' && file[lastPoint+3] == L's')
				{ // ikeliam playlista
					playlist.loadPlaylist(temp.filePath);
				}
				else
				{ // ikeliam faila
					WCHAR filename[MAX_PATH];
					int counter = 0;
					for(int i = lastSlash+1; i < lastPoint; i++)
					{
						filename[counter++] = file[i];
					}
					filename[counter++] = '\0';

					temp.name = filename;
					temp.length = 0;
					playlist.add(temp);
				}
				
				
				n++;
			}		
			DragFinish( query );
			//playlist.setAddRunning(false);
			playlistMenu->Update();
			break;
		}

	case WM_COPYDATA:
		{
			bool resetPlayer = false;
			if(lastFileAddTime < timeGetTime()-100) 
			{
				//playlist.loadPlaylist(L"non_existing.pls");
				playlist.clearPlaylist();
				resetPlayer = true;
			}
			

			COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)lParam;
			if (pcds->dwData == 1)
			{
				LPWSTR lpszString = (LPWSTR)(pcds->lpData);
				// do something with lpszString...

				



				WCHAR file[MAX_PATH];
				for(int i = 0; i < MAX_PATH; i++)
				{
					file[i] = lpszString[i];
				}

				/*MessageBox(NULL,
						file,
						_T("Zinute is kito proceso"),
						MB_OK | MB_TOPMOST | MB_ICONINFORMATION);*/

				
				MusicFileData temp;
				temp.filePath = file;


				int lastSlash = 0;
				int lastPoint = MAX_PATH;
				for(int i = 0; i < MAX_PATH; i ++)
				{
					if(file[i] == L'\\')
					{
						lastSlash = i;
					}
					if(file[i] == L'\0') break;
				}
				

				for(int i = lastSlash; i < MAX_PATH; i ++)
				{
					
					if(file[i] == L'.')
					{
						lastPoint = i; //break;
					}
					if(file[i] == L'\0') break;
				}
				if(file[lastPoint+1] == L'p' && file[lastPoint+2] == L'l' && file[lastPoint+3] == L's')
				{ // ikeliam playlista
					playlist.loadPlaylist(temp.filePath);
				}
				else
				{ // ikeliam faila
					WCHAR filename[MAX_PATH];
					int counter = 0;
					for(int i = lastSlash+1; i < lastPoint; i++)
					{
						filename[counter++] = file[i];
					}
					filename[counter++] = '\0';

					temp.name = filename;
					temp.length = 0;
					playlist.add(temp);
				}
				



			}
			SetFocus(hWnd);
			if(resetPlayer)
			{
				MusicFileData d;			
				playlist.setSongPlace(0);
				d = playlist.getCurrentSong();
				player->load(d.filePath);
			}


			if(playlistMenu != NULL)
			{
				playlistMenu->Update();
			}

			lastFileAddTime = timeGetTime();

			break;
		}

	case WM_MOUSEACTIVATE:
		{
			//LPPOINT lpPoint = new POINT;
			//GetCursorPos(lpPoint);
			//ScreenToClient(progresbar, lpPoint);

			////// patikrinam ar judinamas progres baras
			////if((lpPoint->x >= 0) && (lpPoint->x <= progBarWidth) && (lpPoint->y >= 0) && (lpPoint->y <= progBarHeight))
			////{
			////	player->setProgres(((float)lpPoint->x)*100/progBarWidth/100);
			////}
			//
			//GetCursorPos(lpPoint);
			//ScreenToClient(soundbar, lpPoint);
			//// patikrinam ar judinamas sound baras
			//if((lpPoint->x >= 0) && (lpPoint->x <= soundBarWidth) && (lpPoint->y >= 0) && (lpPoint->y <= soundBarHeight))
			//{
			//	player->setVolume(((float)lpPoint->x)*100/soundBarWidth/100);
			//}
			//
			//			
			//delete[] lpPoint;
			SetFocus(hWnd);
			break;
		}

	case WM_LBUTTONDOWN:
		{
			playlistMenu->scroll(0, false);
			playlistMenu->doubleClick();
			
			//config.setInt("VisualizationID", stulpeliai->click());
			
			GetCursorPos(tmpPoint);

			LPPOINT p = new POINT;
			GetCursorPos(p);
			ScreenToClient(hWnd, p);

			if(p->y <=13 && p->x > 34 && p->x < windowWidth-24-1)
			{
				mButtonDown = true;

				RECT rec;
				
				if(GetWindowRect(hWnd, &rec)){
				
				
				tmX = rec.left;
				tmY = rec.top;

				GetCursorPos(p);
				tmpPoint->x = p->x;
				tmpPoint->y = p->y;

				//SetFocus(hWnd);
				}
				
			}
			delete[] p;
			break;
		}

	case WM_LBUTTONUP:
		{
			mButtonDown = false;
			break;
		}

	case WM_LBUTTONDBLCLK:
		{
			//basePanel.OnDblClick();

			slidingText->OnDblClick();

			int ret = playlistMenu->doubleClick();
			if(ret != -1)
			{
				MusicFileData d;						
				d = playlist.getSong(ret);
				player->load(d.filePath);
				playlist.setSongPlace(ret);
				//if(!playlist.isShufled())
					config.setInt("LastSongId", ret);
				//else
					//config.setInt("LastSongId", 0);
			}
			break;
		}


		case WM_INPUT:
			{
				// Determine how big the buffer should be
				UINT bufferSize;
				GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof (RAWINPUTHEADER));

				// Create a buffer of the correct size - but see note below
				BYTE *buffer=new BYTE[bufferSize];

				// Call the function again, this time with the buffer to get the data
				GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)buffer, &bufferSize, sizeof (RAWINPUTHEADER));

				RAWINPUT *raw = (RAWINPUT*) buffer;

				if (raw->header.dwType == RIM_TYPEMOUSE)
				// read the mouse data
				{				
					if(raw->data.mouse.usButtonData != 0)
					{
						if((SHORT)raw->data.mouse.usButtonData > 0)
						{
							playlistMenu->scroll(-1, false);
						}
						else
						{
							playlistMenu->scroll(1, false);
						}
					}

					


					if(raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN)
					{
						//progressBar->mouseDown();
						//soundBar->mouseDown();
						//playlistMenu->MouseDown();


						basePanel.MouseDown();

						//for(int i = 0; i < buttons_count; i ++)
						//{
						//	//buttons[i]->click();
						//}
					}

					if(raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP)
					{
						//progressBar->mouseUp();
						//soundBar->mouseUp();
						//playlistMenuOLD->mouseUp();


						basePanel.MouseUp();
					}



				}

				if (raw->header.dwType== RIM_TYPEKEYBOARD)
				// read the keyboard data
				{
					USHORT keyCode=raw->data.keyboard.VKey;
					bool keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
					switch(keyCode)
					{
					case VK_UP:
						{
							if(!keyUp)
							{
								playlistMenu->scroll(-1, true);
							}
							break;
						}

					case VK_DOWN:
						{
							if(!keyUp)
							{
								playlistMenu->scroll(1, true);
							}
							break;
						}
					case VK_MEDIA_PLAY_PAUSE:
						{
							if(!keyUp)
							{
								if(player->getPaused()) 
								{
									player->play();
									//SendMessage(progresbar, 0x400 + 16, PBST_ERROR, 0);
								}
								else
								{
									player->pause();
									//SendMessage(progresbar, 0x400 + 16, PBST_PAUSED, 0);
								}
							}
							break;
						}

					case VK_MEDIA_STOP:
						{
							if(!keyUp)
							{				
								player->stop();		
							}
							break;
						}

					case VK_MEDIA_NEXT_TRACK:
						{
							if(!keyUp)
							{				
								MusicFileData d;						
								d = playlist.next();
								player->load(d.filePath);
							}
							break;
						}

					case VK_MEDIA_PREV_TRACK:
						{
							if(!keyUp)
							{				
								MusicFileData d;						
								d = playlist.prev();
								player->load(d.filePath);
								nextForward = false;
							}
							break;
						}

					case VK_DELETE:
						{
							if(!keyUp)
							{
								playlist.deleteSong(playlistMenu->getSelection()); // sitas gauna pasirinktos dainos ID 
								playlistMenu->Update();
							}
							break;
						}

					case VK_ESCAPE:
						{

							//openfilename("save");

							
							

							break;
						}
					}
				}
				break;
			}

		case WM_COMMAND:
			{
				SetFocus(hWnd);
				switch(wParam) //the ID is wParam
				{
				case ID_BUTTON_PREV:
					{
						MusicFileData d;						
						d = playlist.prev();
						player->load(d.filePath);
						config.setInt("LastSongId", playlist.getCurrentSongId());
						nextForward = false;
						break;
					}

				case ID_BUTTON_PLAY:
					{
						player->play();
						config.setInt("Pause", 0);
						//SendMessage(progresbar, 0x400 + 16, PBST_ERROR, 0);
						break;
					}

				case ID_BUTTON_PAUSE:
					{
						player->pause();
						config.setInt("Pause", 1);
						//SendMessage(progresbar, 0x400 + 16, PBST_PAUSED, 0);
						break;
					}

				case ID_BUTTON_STOP:
					{
						player->stop();
						break;
					}

				case ID_BUTTON_NEXT:
					{
						MusicFileData d;						
						d = playlist.next();
						player->load(d.filePath);
						config.setInt("LastSongId", playlist.getCurrentSongId());
						break;
					}

				case ID_BUTTON_CLOSE:
					{
						playlist.savePlayList(L"playlist.pls");

						DestroyWindow(hWnd);
						break;
					}

				case ID_BUTTON_MINIMIZE:
					{
						
						ShowWindow(hWnd, 2);

						break;
					}

				case ID_BUTTON_HELP:
					{
						
						MessageBox(NULL,
						L"Audio failų grotuvas\n\nKūrėjai:\nDarius Bespalovas, IFF-9\nVilius Bekertas, IFF-9\nArvydas Vainauskas, IFF-9\nMartynas Šustavičius, IFF-9\nKTU 2011\n",
						_T("Apie"),
						MB_OK | MB_TOPMOST | MB_ICONINFORMATION);

						break;
						}

				case ID_BUTTON_SHUFLE:
					{
						if(playlist.isShufled())
						{
							playlist.setShuffle(false, true);
							config.setInt("Shuffle", 0);
							MessageBox(NULL,
							L"Grojaraščio maišymas išjungtas",
							_T(""),
							NULL);
						}
						else
						{
							playlist.setShuffle(true);
							config.setInt("Shuffle", 1);
							MessageBox(NULL,
							L"Grojaraštis išmaišytas",
							_T(""),
							NULL);
						}
						break;
					}


				case ID_BUTTON_LOAD:
					{
						wstring fName = openfilename("open");
						if(fName != L"") playlist.loadPlaylist(fName);

						break;
					}


				case ID_BUTTON_SAVE:
					{
						wstring fName = openfilename("save");
						if(fName != L"") playlist.savePlayList(fName);

						break;
					}

				case ID_VOLUME_BAR:
					{
						player->setVolume(soundSlider->getProgress()/100);
						config.setFloat("SoundLevel", soundSlider->getProgress()/100);
						break;
					}

				case ID_PROGRESS_BAR:
					{
						//player->setProgres(progressBar->getProgress()/100);
						//config.setFloat("LastSongProgress", progressBar->getProgress()/100);

						player->setProgres(progresSlider->getProgress()/100);
						config.setFloat("LastSongProgress", progresSlider->getProgress()/100);

						break;
					}
				}
				break;
			}


    case WM_DESTROY:
        PostQuitMessage(0);
		//PostQuitMessage(WM_QUIT);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}